package com.pearl.generator.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author TangDan
 * @version 1.0
 * @since 2022/6/29
 */
@Slf4j
@ControllerAdvice
public class ExceptionControllerAdvice {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result<?> errorHandler(Exception ex) {
        ex.printStackTrace();
        return Result.fail(ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public Result<?> bindException(BindException bindException) {
        bindException.printStackTrace();
        return Result.fail(ResultEnum.FAIL.getCode(), bindException.getBindingResult().getFieldError().getDefaultMessage(), null);
    }

    @ResponseBody
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<?> bindException(IllegalArgumentException ex) {
        ex.printStackTrace();
        return Result.fail(ResultEnum.FAIL.getCode(), ex.getLocalizedMessage(), null);
    }

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public Result<?> businessException(BusinessException businessException) {
        businessException.printStackTrace();
        return Result.fail(ResultEnum.FAIL.getCode(), businessException.getMessage(), null);
    }

}
